<template>
    <view class="chat">
        <!-- 顶部导航栏 -->
        <uni-nav-bar
            :title="serviceInfo?.name || 'AI助手'"
            :status-bar="true"
            fixed
            @clickLeft="showUserMenu"
        >
            <template #left>
                <view class="user-info">
                    <image class="avatar" :src="userInfo?.avatar || '/static/images/default-avatar.png'" mode="aspectFill" />
                </view>
            </template>
            <template #right>
                <view class="status" :class="serviceInfo?.status?.toLowerCase()">
                    {{ getStatusText(serviceInfo?.status) }}
                </view>
            </template>
        </uni-nav-bar>

        <!-- 聊天内容区 -->
        <scroll-view 
            class="message-list" 
            scroll-y 
            :scroll-top="scrollTop"
            @scrolltoupper="loadMoreMessages"
        >
            <uni-load-more v-if="loading" status="loading" />
            <view 
                v-for="message in messages" 
                :key="message.messageId"
                class="message-item"
                :class="{ 'message-self': message.senderId === userInfo?.id }"
            >
                <image 
                    class="avatar"
                    :src="message.senderId === userInfo?.id ? userInfo?.avatar : serviceInfo?.avatar"
                    mode="aspectFill"
                />
                <view class="message-content">
                    <text class="message-text">{{ message.content }}</text>
                    <text class="message-time">{{ formatTime(message.timestamp) }}</text>
                </view>
            </view>
        </scroll-view>

        <!-- 输入区域 -->
        <view class="input-area">
            <view class="toolbar">
                <uni-icons type="emotion" size="24" @click="showEmojiPicker" />
                <uni-icons type="camera" size="24" @click="chooseImage" />
            </view>
            <uni-easyinput
                v-model="inputMessage"
                type="textarea"
                placeholder="请输入消息..."
                :maxlength="500"
                @confirm="sendMessage"
            />
            <button class="send-btn" @click="sendMessage">发送</button>
        </view>

        <!-- 用户菜单弹窗 -->
        <uni-popup ref="userMenu" type="bottom">
            <view class="popup-content">
                <view class="user-profile">
                    <image class="avatar" :src="userInfo?.avatar || '/static/images/default-avatar.png'" mode="aspectFill" />
                    <view class="info">
                        <text class="username">{{ userInfo?.username }}</text>
                        <text class="email">{{ userInfo?.email }}</text>
                    </view>
                </view>
                <view class="menu-list">
                    <view class="menu-item" @click="showMoreOptions">
                        <uni-icons type="more-filled" size="20" />
                        <text>更多选项</text>
                    </view>
                    <view class="menu-item" @click="showSettings">
                        <uni-icons type="gear" size="20" />
                        <text>设置</text>
                    </view>
                    <view class="menu-item" @click="handleLogout">
                        <uni-icons type="logout" size="20" />
                        <text>退出登录</text>
                    </view>
                </view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
import { formatTime } from '@/utils/date';
import {
    sendMessage,
    loadMessages,
    endSession,
    clearChatHistory,
    checkSession,
    createSession,
    evaluateSession,
    logout
} from '@/api/chat';
import websocketClient from '@/utils/websocket';

export default {
    data() {
        return {
            userInfo: null,
            serviceInfo: null,
            sessionInfo: null,
            messages: [],
            inputMessage: '',
            scrollTop: 0,
            loading: false,
            emojis: ['😊', '😂', '😍', '🤔', '👍', '❤️', '😭', '😡', '🎉', '🙏'],
            websocketConnected: false,
            reconnecting: false
        };
    },

    computed: {
        hasMessages() {
            return this.messages && this.messages.length > 0;
        }
    },

    methods: {
        formatTime,
        
        getStatusText(status) {
            const statusMap = {
                'ONLINE': '在线',
                'BUSY': '忙碌',
                'OFFLINE': '离线'
            };
            return statusMap[status] || status;
        },

        showUserMenu() {
            this.$refs.userMenu.open();
        },

        showSettings() {
            uni.navigateTo({
                url: '/pages/settings/index'
            });
        },

        handleLogout() {
            uni.showModal({
                title: '退出登录',
                content: '确定要退出登录吗？',
                success: async (res) => {
                    if (res.confirm) {
                        try {
                            // 断开WebSocket连接
                        websocketClient.disconnect();
                            
                            // 调用退出登录API
                            const success = await logout();
                            if (!success) {
                                throw new Error('退出登录失败');
                            }
                            
                            // 清除本地存储
                        uni.clearStorageSync();
                            
                            // 跳转到登录页
                        uni.reLaunch({
                            url: '/pages/login/index'
                        });
                        } catch (error) {
                            console.error('退出登录失败:', error);
                            uni.showToast({
                                title: '退出登录失败',
                                icon: 'none'
                            });
                        }
                    }
                }
            });
        },

        async initChat() {
            try {
                const sessionRes = await checkSession();
                console.log('检查会话响应:', sessionRes);
                
                if (sessionRes && sessionRes.data) {
                    this.sessionInfo = sessionRes.data;
                    websocketClient.setSessionId(this.sessionInfo.sessionId);
                    
                    if (this.sessionInfo.serviceId) {
                        this.serviceInfo = await this.getServiceInfo(this.sessionInfo.serviceId);
                    }
                    await this.loadMessages();
                } else {
                    console.log('没有活跃会话，准备创建新会话');
                    const newSession = await createSession();
                    console.log('创建新会话响应:', newSession);
                    
                    if (newSession && newSession.data) {
                        console.log('成功获取新会话数据:', newSession.data);
                        this.sessionInfo = newSession.data;
                        websocketClient.setSessionId(this.sessionInfo.sessionId);
                        await this.loadMessages();
                    } else {
                        console.error('创建会话响应格式不正确:', newSession);
                        throw new Error('创建会话失败: 响应格式不正确');
                    }
                }
                
                await this.connectWebSocket();
            } catch (error) {
                console.error('初始化聊天失败:', error);
                console.error('错误详情:', {
                    message: error.message,
                    stack: error.stack,
                    response: error.response
                });
                uni.showToast({
                    title: '初始化聊天失败',
                    icon: 'error'
                });
            }
        },
        
        async connectWebSocket() {
            try {
                if (!this.userInfo || !this.userInfo.userId) {
                    throw new Error('用户信息不完整，无法建立WebSocket连接');
                }
                
                if (websocketClient.isConnected) {
                    console.log('WebSocket已连接');
                    this.websocketConnected = true;
                    return;
                }
                
                this.reconnecting = true;
                
                await websocketClient.connect(this.userInfo.userId);
                this.websocketConnected = true;
                this.reconnecting = false;
                
                console.log('WebSocket连接成功');
            } catch (error) {
                console.error('WebSocket连接失败:', error);
                this.reconnecting = false;
                
                uni.showToast({
                    title: '聊天连接失败，请重试',
                    icon: 'none',
                    duration: 2000
                });
            }
        },

        setupWebSocketHandlers() {
            uni.$on('new-chat-message', this.handleNewChatMessage);
            uni.$on('system-message', this.handleSystemMessage);
            uni.$on('error-message', this.handleErrorMessage);
            uni.$on('websocket-disconnected', this.handleWebSocketDisconnect);
            uni.$on('session-rejected', this.handleSessionRejected);
            uni.$on('session-accepted', this.handleSessionAccepted);
            uni.$on('session-ended', this.handleSessionEnded);
        },
        
        clearWebSocketHandlers() {
            uni.$off('new-chat-message', this.handleNewChatMessage);
            uni.$off('system-message', this.handleSystemMessage);
            uni.$off('error-message', this.handleErrorMessage);
            uni.$off('websocket-disconnected', this.handleWebSocketDisconnect);
            uni.$off('session-rejected', this.handleSessionRejected);
            uni.$off('session-accepted', this.handleSessionAccepted);
            uni.$off('session-ended', this.handleSessionEnded);
        },
        
        handleNewChatMessage(message) {
            console.log('收到新聊天消息:', message);
            
            const existingMsg = this.messages.find(m => m.messageId === message.messageId);
            if (existingMsg) {
                console.log('消息已存在，跳过:', message.messageId);
                return;
            }
            
            this.messages.push(message);
            
            this.$nextTick(() => {
                this.scrollToBottom();
            });
            
            this.playMessageSound();
        },
        
        handleSystemMessage(message) {
            console.log('收到系统消息:', message);
            uni.showToast({
                title: message.content,
                icon: 'none',
                duration: 3000
            });
        },
        
        handleErrorMessage(message) {
            console.error('收到错误消息:', message);
            uni.showToast({
                title: message.content || '发生错误',
                icon: 'none',
                duration: 3000
            });
        },
        
        handleWebSocketDisconnect() {
            console.log('WebSocket连接已断开');
            this.websocketConnected = false;
            
            if (!this.reconnecting) {
                uni.showToast({
                    title: '聊天连接已断开，正在重连...',
                    icon: 'none',
                    duration: 2000
                });
            }
        },
        
        playMessageSound() {
            const innerAudioContext = uni.createInnerAudioContext();
            innerAudioContext.src = '/static/sounds/message.mp3';
            innerAudioContext.play();
        },
        
        scrollToBottom() {
            const query = uni.createSelectorQuery().in(this);
            query.select('.message-list').boundingClientRect(data => {
                if (data) {
                    this.scrollTop = data.height * 100;
                }
            }).exec();
        },

        async loadMessages() {
            if (this.loading || !this.sessionInfo) return;
            this.loading = true;
            try {
                const response = await loadMessages(
                    this.sessionInfo.sessionId,
                    this.messages[0]?.messageId
                );
                if (response && response.data && response.data.records) {
                    this.messages = [...response.data.records, ...this.messages];
                    this.scrollTop = 0;
                }
            } catch (error) {
                console.error('加载消息失败:', error);
                uni.showToast({
                    title: '加载消息失败',
                    icon: 'error'
                });
            } finally {
                this.loading = false;
            }
        },

        async sendMessage() {
            if (!this.inputMessage.trim() || !this.sessionInfo) return;
            
            const messageContent = this.inputMessage.trim();
            this.inputMessage = '';
            
            try {
                const tempMessage = {
                    messageId: 'temp_' + Date.now(),
                    sessionId: this.sessionInfo.sessionId,
                    senderId: this.userInfo.userId,
                    senderType: 'USER',
                    content: messageContent,
                    messageType: 'TEXT',
                    timestamp: new Date(),
                    status: 'SENDING'
                };
                
                this.messages.push(tempMessage);
                
                this.$nextTick(() => {
                    this.scrollToBottom();
                });
                
                if (this.websocketConnected) {
                    await websocketClient.sendChatMessage(
                        messageContent, 
                        this.sessionInfo.sessionId, 
                        this.sessionInfo.serviceId
                    );
                } else {
                    await sendMessage(messageContent, this.sessionInfo.sessionId);
                    this.connectWebSocket();
                    await this.loadMessages();
                }
            } catch (error) {
                console.error('发送消息失败:', error);
                uni.showToast({
                    title: '发送失败',
                    icon: 'error'
                });
                
                const failedMsg = this.messages.find(m => m.content === messageContent && m.status === 'SENDING');
                if (failedMsg) {
                    failedMsg.status = 'FAILED';
                }
            }
        },

        showMoreOptions() {
            uni.showActionSheet({
                itemList: ['结束会话', '清空记录', '服务评价'],
                success: async (res) => {
                    switch (res.tapIndex) {
                        case 0:
                            this.handleEndChat();
                            break;
                        case 1:
                            this.handleClearHistory();
                            break;
                        case 2:
                            this.showEvaluation();
                            break;
                    }
                }
            });
        },

        handleEndChat() {
            uni.showModal({
                title: '结束会话',
                content: '确定要结束当前会话吗？',
                success: async (res) => {
                    if (res.confirm) {
                        try {
                            await endSession(this.sessionInfo.sessionId);
                            
                            if (this.websocketConnected) {
                                websocketClient.sendMessage({
                                    type: 'SYSTEM',
                                    content: '会话已结束',
                                    sessionId: this.sessionInfo.sessionId
                                }).catch(console.error);
                            }
                            
                            uni.showToast({
                                title: '会话已结束',
                                icon: 'success'
                            });
                            setTimeout(() => {
                                uni.navigateBack();
                            }, 1500);
                        } catch (error) {
                            uni.showToast({
                                title: '操作失败',
                                icon: 'error'
                            });
                        }
                    }
                }
            });
        },

        handleClearHistory() {
            uni.showModal({
                title: '清空记录',
                content: '确定要清空聊天记录吗？',
                success: async (res) => {
                    if (res.confirm) {
                        try {
                            await clearChatHistory(this.sessionInfo.sessionId);
                            this.messages = [];
                            uni.showToast({
                                title: '记录已清空',
                                icon: 'success'
                            });
                        } catch (error) {
                            uni.showToast({
                                title: '操作失败',
                                icon: 'error'
                            });
                        }
                    }
                }
            });
        },

        showEvaluation() {
            uni.showModal({
                title: '服务评价',
                content: '请对本次服务进行评分(1-5星)',
                editable: true,
                placeholderText: '请输入1-5的数字',
                success: async (res) => {
                    if (res.confirm && res.content) {
                        const score = parseInt(res.content);
                        if (isNaN(score) || score < 1 || score > 5) {
                            uni.showToast({
                                title: '请输入1-5的数字',
                                icon: 'none'
                            });
                            return;
                        }
                        try {
                            await evaluateSession(this.sessionInfo.sessionId, score);
                            uni.showToast({
                                title: '评价成功',
                                icon: 'success'
                            });
                        } catch (error) {
                            uni.showToast({
                                title: '评价失败',
                                icon: 'error'
                            });
                        }
                    }
                }
            });
        },

        showEmojiPicker() {
            uni.showActionSheet({
                itemList: this.emojis,
                success: (res) => {
                    this.inputMessage += this.emojis[res.tapIndex];
                }
            });
        },

        async chooseImage() {
            try {
                const res = await uni.chooseImage({
                    count: 1,
                    sizeType: ['compressed'],
                    sourceType: ['album', 'camera']
                });
                
                if (res.tempFilePaths && res.tempFilePaths.length > 0) {
                    await this.uploadImage(res.tempFilePaths[0]);
                }
            } catch (error) {
                uni.showToast({
                    title: '选择图片失败',
                    icon: 'none'
                });
            }
        },

        async uploadImage(filePath) {
            try {
                const uploadRes = await uni.uploadFile({
                    url: '/chat/upload',
                    filePath: filePath,
                    name: 'file',
                    formData: {
                        sessionId: this.sessionInfo.sessionId
                    }
                });

                const result = JSON.parse(uploadRes.data);
                if (result.code === 200) {
                    await this.sendMessage(result.data.url, 'IMAGE');
                } else {
                    throw new Error(result.message);
                }
            } catch (error) {
                uni.showToast({
                    title: '上传图片失败',
                    icon: 'none'
                });
            }
        },
        
        async getServiceInfo(serviceId) {
            try {
                const res = await uni.request({
                    url: `/api/service/${serviceId}`,
                    method: 'GET'
                });
                
                if (res.statusCode === 200 && res.data) {
                    return res.data;
                }
                
                return {
                    id: serviceId,
                    name: '客服人员',
                    avatar: '/static/images/service-avatar.png',
                    status: 'ONLINE'
                };
            } catch (error) {
                console.error('获取客服信息失败:', error);
                return {
                    id: serviceId,
                    name: '客服人员',
                    avatar: '/static/images/service-avatar.png',
                    status: 'ONLINE'
                };
            }
        },

        handleSessionRejected(message) {
            console.log('会话被拒绝:', message);
            
            uni.showModal({
                title: '会话已被拒绝',
                content: `客服拒绝了您的会话请求，原因：${message.content || '客服当前无法接待'}`,
                showCancel: false,
                success: () => {
                    const systemMessage = {
                        messageId: 'system_' + Date.now(),
                        sessionId: this.sessionInfo?.sessionId,
                        senderId: 'system',
                        senderType: 'SYSTEM',
                        content: `会话已被拒绝，原因：${message.content || '客服当前无法接待'}`,
                        messageType: 'SYSTEM',
                        timestamp: new Date(),
                        status: 'SENT'
                    };
                    
                    this.messages.push(systemMessage);
                    this.scrollToBottom();
                    
                    setTimeout(() => {
                        uni.navigateBack();
                    }, 2000);
                }
            });
        },

        handleSessionAccepted(message) {
            console.log('会话已被接受:', message);
            
            if (message.serviceId && message.serviceName) {
                this.serviceInfo = {
                    id: message.serviceId,
                    name: message.serviceName,
                    avatar: '/static/images/service-avatar.png',
                    status: 'ONLINE'
                };
            }
            
            const systemMessage = {
                messageId: 'system_' + Date.now(),
                sessionId: this.sessionInfo?.sessionId,
                senderId: 'system',
                senderType: 'SYSTEM',
                content: message.content || `您的会话已被客服${message.serviceName || ''}接受`,
                messageType: 'SYSTEM',
                timestamp: new Date(),
                status: 'SENT'
            };
            
            this.messages.push(systemMessage);
            this.scrollToBottom();
            
            uni.showToast({
                title: '客服已接受会话',
                icon: 'success'
            });
        },

        handleSessionEnded(message) {
            console.log('会话已结束:', message);
            
            const systemMessage = {
                messageId: 'system_' + Date.now(),
                sessionId: this.sessionInfo?.sessionId,
                senderId: 'system',
                senderType: 'SYSTEM',
                content: message.content || '会话已结束',
                messageType: 'SYSTEM',
                timestamp: new Date(),
                status: 'SENT'
            };
            
            this.messages.push(systemMessage);
            this.scrollToBottom();
            
            uni.showModal({
                title: '会话已结束',
                content: message.content || '会话已结束，感谢您的使用',
                showCancel: false,
                success: () => {
                    uni.navigateBack();
                }
            });
        },
    },

    async onLoad() {
        const userInfo = uni.getStorageSync('userInfo');
        if (!userInfo) {
            uni.showToast({
                title: '请先登录',
                icon: 'none'
            });
            setTimeout(() => {
                uni.navigateTo({
                    url: '/pages/login/index'
                });
            }, 1500);
            return;
        }
        
        this.userInfo = userInfo;
        
        this.setupWebSocketHandlers();
        
        await this.initChat();
    },

    onShow() {
        if (this.sessionInfo && !this.websocketConnected && !this.reconnecting) {
            this.connectWebSocket();
        }
    },

    onHide() {
    },

    onUnload() {
        this.clearWebSocketHandlers();
    }
};
</script>

<style lang="scss">
.chat {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background-color: #f5f6fa;
    padding-top: 88rpx;

    .user-info {
        display: flex;
        align-items: center;
        padding: 0 20rpx;

        .avatar {
            width: 60rpx;
            height: 60rpx;
            border-radius: 50%;
        }
    }

    .status {
        font-size: 24rpx;
        padding: 4rpx 12rpx;
        border-radius: 20rpx;
        margin-right: 20rpx;

        &.online {
            background-color: #e8f5e9;
            color: #4caf50;
        }

        &.busy {
            background-color: #fff3e0;
            color: #ff9800;
        }

        &.offline {
            background-color: #f5f5f5;
            color: #9e9e9e;
        }
    }

    .message-list {
        flex: 1;
        padding: 20rpx;
        overflow-y: auto;

        .message-item {
            margin-bottom: 30rpx;
            display: flex;
            align-items: flex-start;
            gap: 20rpx;

            &.message-self {
                flex-direction: row-reverse;

                .message-content {
                    background-color: #1976d2;
                    color: #fff;
                    border-radius: 20rpx 4rpx 20rpx 20rpx;

                    .message-time {
                        color: rgba(255, 255, 255, 0.8);
                    }
                }
            }

            .avatar {
                width: 80rpx;
                height: 80rpx;
                border-radius: 50%;
            }

            .message-content {
                max-width: 60%;
                padding: 20rpx;
                background-color: #f5f5f5;
                border-radius: 4rpx 20rpx 20rpx 20rpx;

                .message-text {
                    font-size: 28rpx;
                    line-height: 1.5;
                    word-break: break-all;
                }

                .message-time {
                    font-size: 24rpx;
                    color: #999;
                    margin-top: 10rpx;
                }
            }
        }
    }

    .input-area {
        padding: 20rpx;
        border-top: 2rpx solid #eee;
        background-color: #fff;

        .toolbar {
            display: flex;
            gap: 20rpx;
            margin-bottom: 10rpx;
            padding: 0 20rpx;
        }

        .send-btn {
            width: 120rpx;
            height: 80rpx;
            background-color: #1976d2;
            color: #fff;
            border: none;
            border-radius: 8rpx;
            font-size: 28rpx;
            float: right;
            margin-top: 10rpx;
        }
    }

    .popup-content {
        background-color: #fff;
        border-radius: 20rpx 20rpx 0 0;
        padding: 30rpx;

        .user-profile {
            display: flex;
            align-items: center;
            gap: 20rpx;
            padding-bottom: 30rpx;
            border-bottom: 2rpx solid #eee;

            .avatar {
                width: 120rpx;
                height: 120rpx;
                border-radius: 50%;
            }

            .info {
                .username {
                    font-size: 32rpx;
                    font-weight: bold;
                    color: #333;
                }

                .email {
                    font-size: 24rpx;
                    color: #666;
                    margin-top: 8rpx;
                }
            }
        }

        .menu-list {
            padding-top: 20rpx;

            .menu-item {
                display: flex;
                align-items: center;
                gap: 20rpx;
                padding: 20rpx 0;
                border-bottom: 2rpx solid #eee;

                &:last-child {
                    border-bottom: none;
                }

                text {
                    font-size: 28rpx;
                    color: #333;
                }
            }
        }
    }
}
</style> 